package com.longway.common.interceptor;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.LogKit;
import com.longway.common.constant.Const;
import com.longway.common.kit.JStrKit;
import com.longway.common.model.BaseOperationLog;
import com.longway.common.model.BaseUser;
import com.longway.common.service.BusinessService;
import com.longway.core.toolbox.Func;
import com.longway.core.toolbox.annotation.DoLog;

public class OperationLogInterceptor implements Interceptor {

	@Override
    public void intercept(Invocation inv) {
		if(!BusinessService.me.isDoLog()){
			inv.invoke();
		}else{
			Method method = inv.getMethod();
			String methodName = method.getName();
			DoLog doLog = method.getAnnotation(DoLog.class);
			if (!isWriteLog(methodName)&& null == doLog) {
				inv.invoke();
			} else {
				BaseUser user = inv.getController().getAttr(Const.loginAccountCacheName);
				if (null == user) {
					inv.invoke();
				}
				String className = inv.getTarget().getClass().getName();
				StringBuilder sb = new StringBuilder();
				HttpServletRequest request = inv.getController().getRequest();
				Enumeration<String> paraNames = request.getParameterNames();
				String key,value;
				while (paraNames.hasMoreElements()){
					key = paraNames.nextElement();
					value = request.getParameter(key);
					Func.builder(sb, key, "=", value, "&");
				}
				if(Func.isEmpty(sb.toString())) {
					Func.builder(sb, request.getQueryString());
				}
				try {
					String msg = Func.format("[类名]:{}  [方法]:{}  [参数]:{}",className, methodName,JStrKit.removeSuffix(sb.toString(), "&"));
					BaseOperationLog baseOperationLog = new BaseOperationLog();
					baseOperationLog.setCreateTime(new Date());
					baseOperationLog.setSucceed(1);
					baseOperationLog.setUserId(user.getId());
					baseOperationLog.setLogName(getLogName(methodName));
					baseOperationLog.setClassName(className);
					baseOperationLog.setMessage(msg);
					baseOperationLog.setOperator(methodName);
					BusinessService.me.saveLog(baseOperationLog);
				} catch (Exception e) {
					e.printStackTrace();
					LogKit.error("异常日志",e);
				}
				inv.invoke();
			}
		}
	}
	
	private boolean isWriteLog(String method) {
		String[] pattern = BusinessService.me.logPatten();
		for (String s : pattern) {
			if (method.indexOf(s) > -1) {
				return true;
			}
		}
		return false;
	}

	private String getLogName(String method) {
		String[] pattern = BusinessService.me.logPatten();
		for (String s : pattern) {
			if (method.indexOf(s) > -1) {
				return BusinessService.me.logMaps().getStr(s);
			}
		}
		return "";
	}
}



